package com.trace.demo.controller;

import com.trace.demo.entity.FarmingActivity;
import com.trace.demo.entity.FarmingInfo;
import com.trace.demo.entity.User;
import com.trace.demo.repository.FarmingActivityRepository;
import com.trace.demo.repository.FarmingInfoRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.HashMap;

/**
 * 种植信息控制器
 */
@RestController
@RequestMapping("/api/farming")
public class FarmingController {

    private final FarmingInfoRepository farmingInfoRepository;
    private final FarmingActivityRepository farmingActivityRepository;
    private final UserRepository userRepository;

    @Autowired
    public FarmingController(FarmingInfoRepository farmingInfoRepository,
                            FarmingActivityRepository farmingActivityRepository,
                            UserRepository userRepository) {
        this.farmingInfoRepository = farmingInfoRepository;
        this.farmingActivityRepository = farmingActivityRepository;
        this.userRepository = userRepository;
    }

    /**
     * 分页获取所有种植信息
     *
     * @param page 页码
     * @param size 每页大小
     * @param sort 排序字段
     * @param direction 排序方向
     * @param keyword 关键词搜索
     * @return 分页种植信息列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllFarmingInfo(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @RequestParam(required = false) String keyword) {

        try {
            // 创建排序对象
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ? Sort.Direction.DESC : Sort.Direction.ASC;
            Sort sortObj = Sort.by(sortDirection, sort);

            // 创建分页对象
            PageRequest pageRequest = PageRequest.of(page, size, sortObj);

            // 查询种植信息列表
            Page<FarmingInfo> farmingInfoPage;

            if (keyword != null && !keyword.isEmpty()) {
                // 根据关键词搜索名称或批次号
                farmingInfoPage = farmingInfoRepository.findByNameContainingOrBatchIdContaining(keyword, keyword, pageRequest);
            } else {
                // 无过滤条件
                farmingInfoPage = farmingInfoRepository.findAll(pageRequest);
            }

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("content", farmingInfoPage.getContent());
            responseData.put("totalElements", farmingInfoPage.getTotalElements());
            responseData.put("totalPages", farmingInfoPage.getTotalPages());
            responseData.put("currentPage", farmingInfoPage.getNumber());
            responseData.put("size", farmingInfoPage.getSize());

            return ResponseEntity.ok(new ApiResponse<>(true, "获取种植信息列表成功", responseData));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取种植信息列表失败: " + e.getMessage(), null));
        }
    }

    /**
     * 保存种植信息
     * @param userId 用户ID
     * @param farmingInfo 种植信息
     * @return 保存的种植信息
     */
    @PostMapping("/info/user/{userId}")
    @Transactional
    public ResponseEntity<ApiResponse<FarmingInfo>> saveFarmingInfo(
            @PathVariable Long userId,
            @RequestBody FarmingInfo farmingInfo) {
        try {
            Optional<User> userOptional = userRepository.findById(userId);

            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }

            User user = userOptional.get();
                        farmingInfo.setUser(user);

                        // 生成批次ID，如果没有提供
                        if (farmingInfo.getBatchId() == null || farmingInfo.getBatchId().isEmpty()) {
                            String batchId = "FARM-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
                            farmingInfo.setBatchId(batchId);
                        }

            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            farmingInfo.setCreatedAt(now);
            farmingInfo.setUpdatedAt(now);

                        FarmingInfo savedInfo = farmingInfoRepository.save(farmingInfo);

                        // 创建一条种植活动记录
                        FarmingActivity activity = new FarmingActivity();
                        activity.setUser(user);
                        activity.setType("farming");
                        activity.setContent("添加了新的种植信息: " + farmingInfo.getName());

                        farmingActivityRepository.save(activity);

            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(new ApiResponse<>(true, "种植信息创建成功", savedInfo));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "保存种植信息失败: " + e.getMessage(), null));
        }
    }

    /**
     * 根据用户ID获取种植信息列表
     * @param userId 用户ID
     * @param page 页码
     * @param size 每页大小
     * @return 种植信息列表
     */
    @GetMapping("/info/user/{userId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getFarmingInfoByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sort,
            @RequestParam(defaultValue = "desc") String direction) {
        try {
            // 验证用户是否存在
            if (!userRepository.existsById(userId)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在: " + userId, null));
            }

            // 创建排序对象
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ? Sort.Direction.DESC : Sort.Direction.ASC;
            Sort sortObj = Sort.by(sortDirection, sort);

            // 创建分页对象
            PageRequest pageRequest = PageRequest.of(page, size, sortObj);

            // 查询用户的种植信息列表
            Page<FarmingInfo> farmingInfoPage = farmingInfoRepository.findByUserId(userId, pageRequest);

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("content", farmingInfoPage.getContent());
            responseData.put("totalElements", farmingInfoPage.getTotalElements());
            responseData.put("totalPages", farmingInfoPage.getTotalPages());
            responseData.put("currentPage", farmingInfoPage.getNumber());
            responseData.put("size", farmingInfoPage.getSize());

            return ResponseEntity.ok(new ApiResponse<>(true, "获取种植信息列表成功", responseData));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取种植信息列表失败: " + e.getMessage(), null));
        }
    }

    /**
     * 根据种植信息ID获取详情
     * @param infoId 种植信息ID
     * @return 种植信息详情
     */
    @GetMapping("/info/{infoId}")
    public ResponseEntity<ApiResponse<FarmingInfo>> getFarmingInfoById(@PathVariable Long infoId) {
        Optional<FarmingInfo> farmingInfoOptional = farmingInfoRepository.findById(infoId);

        if (!farmingInfoOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "种植信息不存在: " + infoId, null));
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "获取种植信息成功", farmingInfoOptional.get()));
    }

    /**
     * 根据批次ID获取种植信息
     * @param batchId 批次ID
     * @return 种植信息
     */
    @GetMapping("/info/batch/{batchId}")
    public ResponseEntity<ApiResponse<FarmingInfo>> getFarmingInfoByBatchId(@PathVariable String batchId) {
        Optional<FarmingInfo> farmingInfoOptional = farmingInfoRepository.findByBatchId(batchId);

        if (!farmingInfoOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "未找到批次ID为 " + batchId + " 的种植信息", null));
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "获取种植信息成功", farmingInfoOptional.get()));
    }

    /**
     * 更新种植信息
     * @param infoId 种植信息ID
     * @param farmingInfo 更新的种植信息
     * @return 更新后的种植信息
     */
    @PutMapping("/info/{infoId}")
    @Transactional
    public ResponseEntity<ApiResponse<FarmingInfo>> updateFarmingInfo(
            @PathVariable Long infoId,
            @RequestBody FarmingInfo farmingInfo) {
        try {
            Optional<FarmingInfo> existingInfoOptional = farmingInfoRepository.findById(infoId);

            if (!existingInfoOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "种植信息不存在: " + infoId, null));
            }

            FarmingInfo existingInfo = existingInfoOptional.get();
            User user = existingInfo.getUser();

            // 保留原始信息
            farmingInfo.setId(infoId);
            farmingInfo.setUser(user);
            farmingInfo.setCreatedAt(existingInfo.getCreatedAt());
            farmingInfo.setUpdatedAt(LocalDateTime.now());

            // 如果批次ID不为空，则使用新的批次ID，否则保留原来的批次ID
            if (farmingInfo.getBatchId() == null || farmingInfo.getBatchId().isEmpty()) {
                farmingInfo.setBatchId(existingInfo.getBatchId());
            }

            FarmingInfo updatedInfo = farmingInfoRepository.save(farmingInfo);

            // 创建一条更新活动记录
            FarmingActivity activity = new FarmingActivity();
            activity.setUser(user);
            activity.setType("farming");
            activity.setContent("更新了种植信息: " + updatedInfo.getName());

            farmingActivityRepository.save(activity);

            return ResponseEntity.ok(new ApiResponse<>(true, "种植信息更新成功", updatedInfo));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新种植信息失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除种植信息
     * @param infoId 种植信息ID
     * @return 删除结果
     */
    @DeleteMapping("/info/{infoId}")
    @Transactional
    public ResponseEntity<ApiResponse<Void>> deleteFarmingInfo(@PathVariable Long infoId) {
        try {
            Optional<FarmingInfo> farmingInfoOptional = farmingInfoRepository.findById(infoId);

            if (!farmingInfoOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "种植信息不存在: " + infoId, null));
            }

            FarmingInfo farmingInfo = farmingInfoOptional.get();
            User user = farmingInfo.getUser();

            // 记录删除活动
            FarmingActivity activity = new FarmingActivity();
            activity.setUser(user);
            activity.setType("farming");
            activity.setContent("删除了种植信息: " + farmingInfo.getName());

            farmingActivityRepository.save(activity);

            // 删除种植信息
            farmingInfoRepository.deleteById(infoId);

            return ResponseEntity.ok(new ApiResponse<>(true, "种植信息删除成功", null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "删除种植信息失败: " + e.getMessage(), null));
        }
    }

    /**
     * 批量删除种植信息
     * @param ids 种植信息ID列表
     * @return 删除结果
     */
    @DeleteMapping("/info/batch")
    @Transactional
    public ResponseEntity<ApiResponse<Void>> batchDeleteFarmingInfo(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ApiResponse<>(false, "删除失败：未提供ID列表", null));
            }
            
            // 验证所有ID是否存在
            List<FarmingInfo> farmingInfoList = farmingInfoRepository.findAllById(ids);
            if (farmingInfoList.size() != ids.size()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "删除失败：部分ID不存在", null));
            }
            
            // 记录删除活动
            for (FarmingInfo farmingInfo : farmingInfoList) {
                User user = farmingInfo.getUser();
                
                FarmingActivity activity = new FarmingActivity();
                activity.setUser(user);
                activity.setType("farming");
                activity.setContent("删除了种植信息: " + farmingInfo.getName());
                
                farmingActivityRepository.save(activity);
            }
            
            // 批量删除
            farmingInfoRepository.deleteAllById(ids);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "批量删除种植信息成功", null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "批量删除种植信息失败: " + e.getMessage(), null));
        }
    }

    /**
     * 获取农户活动记录
     * @param farmerId 农户ID
     * @return 活动记录列表
     */
    @GetMapping("/activities/{farmerId}")
    public ResponseEntity<ApiResponse<List<FarmingActivity>>> getFarmerActivities(@PathVariable Long farmerId) {
        try {
            // 验证农户是否存在
            if (!userRepository.existsById(farmerId)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "农户不存在: " + farmerId, null));
            }
            
            // 查询农户的活动记录
            List<FarmingActivity> activities = farmingActivityRepository.findByUserIdOrderByTimestampDesc(farmerId);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取农户活动记录成功", activities));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取农户活动记录失败: " + e.getMessage(), null));
        }
    }

    /**
     * 创建错误响应Map
     * @param errorMessage 错误信息
     * @return 错误响应Map
     */
    private Map<String, Object> createErrorMap(String errorMessage) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("error", errorMessage);
        return errorMap;
    }
}
